import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivityProductService } from '@core/routes-services/activity-product.service';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { QCLOUD_DOMAIN, UPLOAD_DOMAIN } from '../../../../constant/config';
import { CacheService } from '@core/routes-services/cache.service';
import { AGENT_BALANCE_TYPE, YESNO_OPTION } from '../../../../constant/dictionary';
import { AgentLevelService } from '@core/routes-services/agent-level.service';

@Component({
  selector: 'app-product-edit',
  templateUrl: './product-edit.component.html',
  styles: [`
    :host ::ng-deep .ant-upload-select-picture-card {
      width: 128px;
      height: 128px;
    }
    :host ::ng-deep .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }
    :host ::ng-deep .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }
    :host ::ng-deep .ant-upload .avatar {
      width: 120px;
      height: 120px;
    }
  `]
})
export class ProductEditComponent implements OnInit {
  id:any = 0 ;
  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = false;

  yesNo = YESNO_OPTION;
  agentBalanceType = AGENT_BALANCE_TYPE;
  uploadDomain = UPLOAD_DOMAIN;
  qcloudDomain = QCLOUD_DOMAIN;
  headers: any = {};
  componentDirty: boolean = false;

  levelOptions: any [] = [];

  @ViewChild('content') content: ElementRef;
  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private cacheService: CacheService,
              private router:Router,
              private activityProductService: ActivityProductService,
              private agentLevelService: AgentLevelService,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.initLevelOptions();
    const token: any = this.cacheService.getTokenInfo();
    this.headers = { 'Authorization': token };
    this.route.queryParams.forEach((params: Params) => {
      this.id = +params['id'];
      this.initEntity();
    });
    this.initValidateForm();
  }


  initLevelOptions() {
    this.agentLevelService.getAll().then((res) => {
      if (res.status.toString().startsWith('20')) {
        this.levelOptions = res.data.agentLevelsList;
      } else {
        this.message.warning(res.message);
      }
    }, error => {
      this.message.error(error.message ? error.message : error.error);
    });
  }
  initValidateForm() {
    this.entity.needAddress = this.entity.needAddress == 1 ? 1 : 2;
    this.entity.needRemark = this.entity.needRemark == 1 ? 1 : 2;
    this.entity.needMarkup = this.entity.needMarkup == 1 ? 1 : 2;
    this.entity.onlyWxpay = this.entity.onlyWxpay == 1 ? 1 : 2;
    this.entity.rechargeType = this.entity.rechargeType == 2 ? 2 : 1;
    let miniFlag = this.entity.levelId?1:2;
    this.validateForm = this.fb.group({
      title: [this.entity.title, [Validators.required, Validators.maxLength(30)]],
      remark: [this.entity.remark, [Validators.maxLength(500)]],
      price: [this.entity.price, [Validators.required]],
      minQuantity: [this.entity.minQuantity, [Validators.required]],
      unit: [this.entity.unit, [Validators.required, Validators.maxLength(6)]],
      sortNum: [this.entity.sortNum, [Validators.required]],
      restrictionNum: [this.entity.restrictionNum, [Validators.required]],
      stock: [this.entity.stock, [Validators.required]],
      miniFlag: [miniFlag, []],//前端字段 是否开通云仓字段
      levelId: [this.entity.levelId, []],
      rechargeNum: [this.entity.rechargeNum, []],
      rechargeType: [this.entity.rechargeType, []],
      description: [this.entity.description, []],
      mainImg: [this.entity.mainImg, [Validators.required]],
      needAddress: [this.entity.needAddress, [Validators.required]],
      needRemark: [this.entity.needRemark, [Validators.required]],
      needMarkup: [this.entity.needMarkup, [Validators.required]],
      onlyWxpay: [this.entity.onlyWxpay, [Validators.required]],
    });
    this.content.nativeElement.innerHTML = this.entity.description ? this.entity.description : '点击进行内容编辑';
  }

  initEntity() {
    if(this.id != 0){
      this.isLoading = true;
      this.activityProductService.detail(this.id).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.entity = res.data;
          this.initValidateForm();
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }

  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      if(this.validateForm.value.restrictionNum != 0 && this.validateForm.value.restrictionNum < this.validateForm.value.minQuantity ){
        this.message.warning("限购数量不能小于起订量")
        return;
      }
      //修改
      if(this.validateForm.dirty || this.componentDirty){
        this.isLoading = true;
        if(this.validateForm.value.miniFlag == 2){
          //选择 不开通云仓账号 清掉对应 levelId 和 rechargeNum 的值
          this.validateForm.value.levelId = null;
          this.validateForm.value.rechargeNum = null;
          this.validateForm.value.rechargeType = null;
        }
        this.activityProductService.saveOrUpdateEntity(this.entity.id, this.validateForm.value).then((res) => {
          if (res.status.toString().startsWith('20')) {
            this.goBack();
          } else {
            this.message.warning(res.message);
          }
          this.isLoading = false;
        }, error => {
          this.message.error(error.message ? error.message : error.error);
          this.isLoading = false;
        });
      }else {
        this.goBack();
      }

    }
  }

  goBack() {
    this.router.navigate(['/mid-autumn/activity-product']);
  }


  isShow:boolean = false;
  showEdit(){
    this.isShow=!this.isShow;
    let body=document.body;
    if(this.isShow){
      body.style.overflow='hidden';
      body.style.userSelect='none';
    }else{
      body.style.overflow='';
      body.style.userSelect='';
    }
  }
  contentCallback(content){
    this.entity.description = content;
    this.content.nativeElement.innerHTML = this.entity.description;
    this.componentDirty = true;
    this.validateForm.controls.description.setValue(content);
  }

  /**
   * 上传图控件 ng-zorro upload
   *
   * @param {any} file
   * @param {any} fileList
   */
  handleChange({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      // console.log(file, fileList);
    }
    if (status === 'done') {
      this.message.success(`${file.name} 上传成功`);
      let findIdx = fileList.findIndex(w => file.lastModified == w.lastModified);
      fileList[findIdx].imgKey = fileList[findIdx].response.data;
      fileList[findIdx].name = fileList[findIdx].response.data;
      fileList[findIdx].url = this.qcloudDomain + fileList[findIdx].response.data;
      this.entity.mainImg = fileList[findIdx].url;
      this.validateForm.controls.mainImg.setValue(this.entity.mainImg);
      this.componentDirty = true;
    } else if (status === 'error') {
      this.message.error(`${file.name} 上传失败`);
    }
  }

}
